package com.contract.spirit.ui.splash

import android.Manifest
import com.contract.commonlib.application.ApplicationProxy
import com.contract.commonlib.base.BaseActivity
import com.contract.commonlib.http.ext.parseState
import com.contract.commonlib.permission.PermissionManager
import com.contract.commonlib.permission.PermissionManager.onPermissiionSuccessListener
import com.contract.commonlib.util.ext.gsonToJson
import com.contract.commonlib.util.ext.showToast
import com.contract.spirit.BuildConfig
import com.contract.spirit.R
import com.contract.spirit.databinding.ActivitySplashBinding
import com.contract.spirit.manage.CommonConfigManager
import com.contract.spirit.ui.login.LoginActivity
import com.contract.spirit.ui.main.MainActivity

/**
 * @author: witness
 * created: 2021/9/18
 * desc:
 */
class SplashActivity : BaseActivity<ActivitySplashBinding, SplashViewModel>(),
    onPermissiionSuccessListener {
    override fun setContentView(): Int {
        return R.layout.activity_splash
    }

    override fun initData() {
        requestPermission()
    }

    private fun requestPermission() {
        PermissionManager.checkPermission(mContext, this, getPermissions())
    }

    private fun getPermissions(): ArrayList<String?>? {
        return arrayListOf(
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
    }

    override fun onPermissionSuccess(requestCode: Int, grantPermissions: List<String>) {
        requestData()
    }

    override fun onPermissionFail(deniedList: List<String>?) {
        showToast(
            "您拒绝了如下权限：${deniedList}请开启权限，以正常使用 ${BuildConfig.APP_NAME}", true
        )
        finish()
    }

    override fun requestData() {
        mViewModel.checkAppUpdate()
    }

    override fun registerNecessaryObserver() {
        mViewModel.versionInfoResponse.observe(this,{ it ->
            parseState(it,{
                CommonConfigManager.configInfo =  gsonToJson(it)
                if (ApplicationProxy.instance!!.isLogin()){
                    goLaunch(mContext,MainActivity::class.java)
                }else{
                   goLaunch(mContext, LoginActivity::class.java)
                }
                finish()
            })
        })
    }
}